package cn.kgc.utils;

import cn.kgc.utils.config.SmsConfig;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.core.http.HttpClient;
import com.aliyun.core.http.HttpMethod;
import com.aliyun.core.http.ProxyOptions;
import com.aliyun.httpcomponent.httpclient.ApacheAsyncHttpClientBuilder;
import com.aliyun.sdk.service.dysmsapi20170525.models.*;
import com.aliyun.sdk.service.dysmsapi20170525.*;
import com.google.gson.Gson;
import darabonba.core.RequestConfiguration;
import darabonba.core.client.ClientOverrideConfiguration;
import darabonba.core.utils.CommonUtil;
import darabonba.core.TeaPair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

//import javax.net.ssl.KeyManager;
//import javax.net.ssl.X509TrustManager;
import java.net.InetSocketAddress;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * 发送短信的工具类
 */
@Component
public class SmsUtils{

 @Autowired
 SmsConfig smsConfig;

 // 模板：SMS_190729100
 // 变量： {code:"1111"}
 // 账户：LTAIh3VhtOA0l9v5
 //密码： Z9zV2b2we2x5pBRRoVdCry5TnJPSGZ
 public String sendSmsCode(String phone,String template,String code) throws ExecutionException, InterruptedException, BaseException {
  StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
          .accessKeyId(smsConfig.getAccessKeyId())
          .accessKeySecret(smsConfig.getAccessKeySecret())
          .build());

  // Configure the Client
  AsyncClient client = AsyncClient.builder()
          .region("cn-hangzhou")
          .credentialsProvider(provider)
          .overrideConfiguration(
                  ClientOverrideConfiguration.create()
                          .setEndpointOverride(smsConfig.getEndpoint())
          )
          .build();

  SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
          .signName("圣乡堂")
          .phoneNumbers(phone)
          .templateParam(code)
          .templateCode(template)
          .build();

  CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
  SendSmsResponse resp = response.get();
  System.out.println(new Gson().toJson(resp));

  client.close();
  String result=response.get().getBody().getCode();
  if(result!=null&&result.equals("OK")){
   return "OK";
  }else{
   throw new BaseException(new IErrorCode() {
    @Override
    public String getErrorCode() {
     return resp.getBody().getCode();
    }

    @Override
    public String getErrorMessage() {
     return  resp.getBody().getMessage();
    }
   });
  }
 }





}
